package com.intel.factorytest;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.DropBoxManager.Entry;
import android.os.Environment;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import com.intel.factorytest.util.Util;



public class ResultDataSave {
    private static final String TAG = "ResultDataSave";
    public static final int ITEM_DONOT_TEST = 0;
    public static final int ITEM_TEST_SUCCES = 1;
    public static final int ITEM_TEST_FAIL = 2;
    public static final int ITEM_EXTERN = 4;

    public static final int SINGLE_ITEM_TEST = 0;
    public static final int SYSTEM_ITEM_TEST = 1;
    public static final int PCB_ITEM_TEST = 2;

    private static final String sep = System.getProperty("file.separator", "/");
    private static final String LogFilePrefix = "MAT_TEST_";
    private static final String LogExtension = ".log";
    private static final String LogTxtExtension = ".txt";
    // protected static List<Integer> mSingleResultData = new
    // ArrayList<Integer>();
    // protected static List<Integer> mSyetemResultData = new
    // ArrayList<Integer>();
    // protected static List<Integer> mPCBResultData = new ArrayList<Integer>();
    public static Map<String, NumAndResult> mSingleResultMap = new HashMap<String, NumAndResult>();
    public static Map<String, NumAndResult> mSyetemResultMap = new HashMap<String, NumAndResult>();
    public static Map<String, NumAndResult> mPCBResultMap = new HashMap<String, NumAndResult>();

    public static List<Map<String, Object>> mLastList;

    private static int iNeedSaveDatabase = 0;
    private static int iNeedSaveFile = 0;

    private DatabaseHelper mHelper = null;

    protected Map<String, NumAndResult> getResultData(int mTestType) {
        if (mTestType == SINGLE_ITEM_TEST) {
            return mSingleResultMap;
        } else if (mTestType == SYSTEM_ITEM_TEST) {
            return mSyetemResultMap;
        } else {
            return mPCBResultMap;
        }
    }

    protected boolean initResultData(Context context, int mTestType,
            List<Map<String, Object>> summarys) {
        Log.d(TAG, "mSyetemResultMap.size()=" + mSyetemResultMap.size()
                + "summarys.size()=" + summarys.size() + "   mTestType"
                + mTestType);
        if (mTestType == SINGLE_ITEM_TEST) {
            if ((mSingleResultMap == null) || (mSingleResultMap.size() == 0)
                    || (mSingleResultMap.size() < summarys.size())) {
                // MapReadResult(mTestType, mSingleResultMap, summarys);
                // mSingleResultMap = new HashMap<String, NumAndResult>();
                ReadResultFromDataBase(context, mTestType, summarys);
                return false;
            }

        } else if (mTestType == SYSTEM_ITEM_TEST) {
            if ((mSyetemResultMap == null) || (mSyetemResultMap.size() == 0)
                    || (mSyetemResultMap.size() < summarys.size())) {
                // MapReadResult(mTestType, mSyetemResultMap, summarys);
                // mSyetemResultMap = new HashMap<String, NumAndResult>();
                ReadResultFromDataBase(context, mTestType, summarys);
                return false;
            }
        } else {
            if ((mPCBResultMap == null) || (mPCBResultMap.size() == 0)
                    || (mPCBResultMap.size() < summarys.size())) {
                // MapReadResult(mTestType, mPCBResultMap, summarys);
                // mPCBResultMap = new HashMap<String, NumAndResult>();
                ReadResultFromDataBase(context, mTestType, summarys);
                return false;
            }
        }
        return true;
    }

    // protected void initResultData(Context context, int mTestType,
    // List<Map<String, Object>> summarys, String absFilename) {
    // if (mTestType == SINGLE_ITEM_TEST) {
    // // mSingleResultMap =
    // if ((mSingleResultMap == null) || (mSingleResultMap.size() == 0)) {
    // MapReadResult(mTestType, mSingleResultMap, summarys);
    // }
    //
    // } else if (mTestType == SYSTEM_ITEM_TEST) {
    // if ((mSingleResultMap == null) || (mSingleResultMap.size()) == 0) {
    // MapReadResult(mTestType, mSyetemResultMap, summarys);
    // }
    // } else {
    // if ((mPCBResultMap == null) || (mPCBResultMap.size()) == 0) {
    // MapReadResult(mTestType, mPCBResultMap, summarys);
    // }
    // }
    //
    // }

    protected void MapReadResult(int mTestType,
            Map<String, NumAndResult> mResultMap,
            List<Map<String, Object>> summarys) {
        String name = null;
        Map map;
        NumAndResult mSaveData = new NumAndResult();
        for (int i = 0; i < summarys.size(); i++) {
            map = (Map) summarys.get(i);
            name = (String) map.get("itemName");

            mSaveData.mNum = i;
            mSaveData.mResult = ITEM_DONOT_TEST;
            mResultMap.put(name, mSaveData);
        }
    }

    protected void ReadResultFromDataBase(Context context, int mTestType,
            List<Map<String, Object>> summarys) {
        String mResultTable;
        Map<String, NumAndResult> mTempMap;
        // mListResult = new ArrayList<Integer>();
        Map map;
        String name = null;
        Cursor cursor = null;
        // Log.d(TAG, "ReadResultFromDataBase");
        mHelper = new DatabaseHelper(context);
        // Log.d(TAG, "new DatabaseHelper(context)");
        SQLiteDatabase db = mHelper.getWritableDatabase();
        if (mTestType == ResultDataSave.SINGLE_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_SINGLE_TEST;
        } else if (mTestType == ResultDataSave.SYSTEM_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_SYSTEM_TEST;
        } else if (mTestType == ResultDataSave.PCB_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_PCB_TEST;
        } else {
            mResultTable = DatabaseHelper.TABLE_SINGLE_TEST;
        }

        if (mTestType == SINGLE_ITEM_TEST) {
            mTempMap = mSingleResultMap;
        } else if (mTestType == SYSTEM_ITEM_TEST) {
            mTempMap = mSyetemResultMap;
        } else {
            mTempMap = mPCBResultMap;
        }

        for (int i = 0; i < summarys.size(); i++) {
            NumAndResult mSaveData = new NumAndResult();
            map = (Map) summarys.get(i);
            name = (String) map.get("itemName");

            // if (mTempMap != null) {
            // if (mTempMap.get(name) != null) {
            // continue;
            // }
            // }
            try {
                cursor = db.query(mResultTable, null,
                        DatabaseHelper.PROJECTION_NAME + "=?",
                        new String[] { name }, null, null, null);
                if (cursor == null || cursor.getCount() == 0) { // cur.moveToFirst()
                    mSaveData.mNum = i;
                    mSaveData.mResult = ITEM_DONOT_TEST;
                } else {
                    cursor.moveToFirst();
                    mSaveData.mNum = cursor.getInt(0);
                    mSaveData.mResult = cursor.getInt(2);
                }

                // mListResult.add(mSaveData.mResult);

                mTempMap.put(name, mSaveData);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
            // Log.d(TAG, "mResultMap.mResult" + mResultMap.get(name).mResult);

            // Log.d(TAG, "mSaveData.mNum:" + mSaveData.mNum + "  username:"
            // + name + "  mSaveData.mResult" + mSaveData.mResult);
        }
        Log.d(TAG, "cursor.close");
        // cursor.close();
        db.close();

    }

    // protected void SaveResultData(int mTestType,
    // List<Map<String, Object>> summarys) {
    //
    // }

    // public Map<String, NumAndResult> readTestResult(String absFilename) {
    // Map<String, NumAndResult> resultMap = new HashMap<String,
    // NumAndResult>();
    // NumAndResult mReadresult = new NumAndResult();
    //
    // File logFile = new File(absFilename);
    // if (!logFile.exists()) {
    // System.out.println(absFilename + " doesn't exist!");
    // return resultMap;
    // }
    //
    // InputStreamReader isr = null;
    // BufferedReader br = null;
    // try {
    // isr = new InputStreamReader(new FileInputStream(logFile), "UTF-8");
    // br = new BufferedReader(isr);
    // String line;
    // String key;
    // String result;
    // while ((line = br.readLine()) != null) {
    // key = line.substring(0, line.length() - 4).trim();
    // result = line.substring(line.length() - 4);
    // // boolean value = (result.equals("Pass")) ? true : false;
    // mReadresult.mNum = 0;
    // if (result.equals("Pass")) {
    // mReadresult.mResult = ITEM_TEST_SUCCES;
    // } else if (result.equals("Fail")) {
    // mReadresult.mResult = ITEM_TEST_FAIL;
    // } else {
    // mReadresult.mResult = ITEM_DONOT_TEST;
    // }
    // resultMap.put(key, mReadresult);
    // }
    // // conn.close();
    // } catch (FileNotFoundException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // } catch (IOException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // } finally {
    // if (isr != null) {
    // try {
    // isr.close();
    // } catch (IOException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // }
    // if (br != null) {
    // try {
    // br.close();
    // } catch (IOException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // }
    // }
    //
    // return resultMap;
    // }

    protected void SaveResultData(Context context, int mTestType,
            List<Map<String, Object>> summarys) {
        String mResultTable;
        Map map;
        String name = null;
        Cursor cursor = null;
        NumAndResult mNumAndResult = new NumAndResult();

        if (iNeedSaveDatabase == 0) {
            Log.d(TAG, "iNeedSaveDatabase ==0");
            return;
        }

        mHelper = new DatabaseHelper(context);
        SQLiteDatabase db = mHelper.getWritableDatabase();
        if (mTestType == ResultDataSave.SINGLE_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_SINGLE_TEST;
        } else if (mTestType == ResultDataSave.SYSTEM_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_SYSTEM_TEST;
        } else if (mTestType == ResultDataSave.PCB_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_PCB_TEST;
        } else {
            mResultTable = DatabaseHelper.TABLE_SINGLE_TEST;
        }

        for (int i = 0; i < summarys.size(); i++) {
            map = (Map) summarys.get(i);
            name = (String) map.get("itemName");
            cursor = db.query(mResultTable, null,
                    DatabaseHelper.PROJECTION_NAME + "=?",
                    new String[] { name }, null, null, null);

            int mResult;
            if (mTestType == SINGLE_ITEM_TEST) {
                mNumAndResult = ((NumAndResult) mSingleResultMap.get(name));
            } else if (mTestType == SYSTEM_ITEM_TEST) {
                mNumAndResult = ((NumAndResult) mSyetemResultMap.get(name));
            } else {
                mNumAndResult = ((NumAndResult) mPCBResultMap.get(name));
            }
            if (mNumAndResult != null) {
                mResult = mNumAndResult.mResult;
            } else {
                mResult = ITEM_DONOT_TEST;
            }

            if (cursor == null || cursor.getCount() == 0) { // cur.moveToFirst()
                ContentValues cv = new ContentValues();
                cv.put(DatabaseHelper.PROJECTION_ID, i);
                cv.put(DatabaseHelper.PROJECTION_NAME, name);
                cv.put(DatabaseHelper.PROJECTION_RESULT, mResult);

                db.insert(mResultTable, DatabaseHelper.PROJECTION_NAME, cv);
            } else {
                ContentValues values = new ContentValues();
                values.put(DatabaseHelper.PROJECTION_ID, i);
                values.put(DatabaseHelper.PROJECTION_NAME, name);
                values.put(DatabaseHelper.PROJECTION_RESULT, mResult);
                String whereClause = "name=?";
                String[] whereArgs = { name };
                db.update(mResultTable, values, whereClause, whereArgs);
            }

            if (cursor != null) {
                cursor.close();
            }
            // Log.d(TAG, "mSaveData.mNum:" + i + "  username:" + name
            // + "  mResult" + mResult);
        }
        Log.d(TAG, "cursor.close");
        // cursor.close();
        db.close();

        iNeedSaveDatabase = 0;
    }

    protected void SaveResultDataByName(Context context, int mTestType,
            int mID, String mItemName, int mResult) {
        String mResultTable;
        Cursor cursor = null;

        setDataOfList(mTestType, mItemName, mID, mResult);

        mHelper = new DatabaseHelper(context);
        SQLiteDatabase db = mHelper.getWritableDatabase();
        if (mTestType == ResultDataSave.SINGLE_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_SINGLE_TEST;
        } else if (mTestType == ResultDataSave.SYSTEM_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_SYSTEM_TEST;
        } else if (mTestType == ResultDataSave.PCB_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_PCB_TEST;
        } else {
            mResultTable = DatabaseHelper.TABLE_SINGLE_TEST;
        }

        cursor = db.query(mResultTable, null, DatabaseHelper.PROJECTION_NAME
                + "=?", new String[] { mItemName }, null, null, null);

        if (cursor == null || cursor.getCount() == 0) { // cur.moveToFirst()
            ContentValues cv = new ContentValues();
            cv.put(DatabaseHelper.PROJECTION_ID, mID);
            cv.put(DatabaseHelper.PROJECTION_NAME, mItemName);
            cv.put(DatabaseHelper.PROJECTION_RESULT, mResult);

            db.insert(mResultTable, DatabaseHelper.PROJECTION_NAME, cv);
        } else {
            ContentValues values = new ContentValues();
            values.put(DatabaseHelper.PROJECTION_ID, mID);
            values.put(DatabaseHelper.PROJECTION_NAME, mItemName);
            values.put(DatabaseHelper.PROJECTION_RESULT, mResult);
            String whereClause = "name=?";
            String[] whereArgs = { mItemName };
            db.update(mResultTable, values, whereClause, whereArgs);
        }
        // Log.d(TAG, "mSaveData.mNum:" + i + "  username:"
        // + name + "  mResult" + mResult);
        Log.d(TAG, "cursor.close");
        cursor.close();
        db.close();
    }
    
    protected void DeleteResult(Context context, int mTestType) {            
        Set<java.util.Map.Entry<String, NumAndResult>> set=mSyetemResultMap.entrySet();
        Iterator<java.util.Map.Entry<String, NumAndResult>> iterator=set.iterator();
        while (iterator.hasNext()) {
             Map.Entry<String, NumAndResult> mapentry = (Map.Entry<String,
             NumAndResult>) iterator.next();
             NumAndResult mTempResult = new NumAndResult();
             mapentry.setValue(mTempResult);
        }
        iNeedSaveDatabase = 1;
    }

    protected void DropTable(Context context, int mTestType) {
//        String mResultTable;
//        mHelper = new DatabaseHelper(context);
//
//        if (mTestType == ResultDataSave.SINGLE_ITEM_TEST) {
//            mResultTable = DatabaseHelper.TABLE_SINGLE_TEST;
//        } else if (mTestType == ResultDataSave.SYSTEM_ITEM_TEST) {
//            mResultTable = DatabaseHelper.TABLE_SYSTEM_TEST;
//        } else if (mTestType == ResultDataSave.PCB_ITEM_TEST) {
//            mResultTable = DatabaseHelper.TABLE_PCB_TEST;
//        } else {
//            mResultTable = DatabaseHelper.TABLE_SINGLE_TEST;
//        }

//        try {
//            SQLiteDatabase db = mHelper.getWritableDatabase();
//            String sql = "DROP TABLE " + mResultTable;
//            db.execSQL(sql);
//            db.close();
//        } catch (Exception ex) {
//
//        }
        
        Log.e(TAG, "DropTable database!");
        
//        SQLiteDatabase db = mHelper.getWritableDatabase();
//        mHelper.onUpgrade(db,0,0);
//        db.close();
        
        Set<java.util.Map.Entry<String, NumAndResult>> set=mSyetemResultMap.entrySet();
        Iterator<java.util.Map.Entry<String, NumAndResult>> iterator=set.iterator();
        while (iterator.hasNext()) {
             Map.Entry<String, NumAndResult> mapentry = (Map.Entry<String,
             NumAndResult>) iterator.next();
             NumAndResult mTempResult = new NumAndResult();
             mapentry.setValue(mTempResult);
        }
        
//        iNeedSaveDatabase = 0;

    }

    protected int getDataOfList(int mTestType, String name) {
        int mResult;
        NumAndResult mNumAndResult = new NumAndResult();
        if (mTestType == SINGLE_ITEM_TEST) {
            mNumAndResult = mSingleResultMap.get(name);

        } else if (mTestType == SYSTEM_ITEM_TEST) {
            mNumAndResult = mSyetemResultMap.get(name);

        } else {
            mNumAndResult = mPCBResultMap.get(name);
        }

        if (mNumAndResult != null) {
            mResult = mNumAndResult.mResult;
        } else {
            mResult = ITEM_DONOT_TEST;
        }

        // Log.d(TAG, "mTestType:" + mTestType + "  username:" + name
        // + "  mResult" + mResult);

        // if ((mResult != ITEM_TEST_SUCCES) || (mResult != ITEM_TEST_FAIL)) {
        // mResult = ITEM_DONOT_TEST;
        // }
        return mResult;
    }

    protected int setDataOfList(int mTestType, String name, int num, int mData) {
        NumAndResult mSaveData = new NumAndResult();
        mSaveData.mNum = num;
        mSaveData.mResult = mData;
        if (mTestType == SINGLE_ITEM_TEST) {
            mSingleResultMap.put(name, mSaveData);
        } else if (mTestType == SYSTEM_ITEM_TEST) {
            mSyetemResultMap.put(name, mSaveData);
        } else {
            mPCBResultMap.put(name, mSaveData);
        }

        iNeedSaveDatabase = 1;
        iNeedSaveFile = 1;

        // Log.d(TAG, "mTestType:" + mTestType + "  username:" + name
        // + "  mSaveData.mResult" + mSaveData.mResult);

        return 1;
    }

    protected String SaveResultToFile(int mTestType) throws IOException {
        StringBuilder sb = new StringBuilder("");
        String sCurrentTime = "";
        String sRandomData = "";
        Random mRandom = new Random();
        String tempath = "";
        String tempathend = "";
        String sLogDirend = "";
        String sFileNameEnd = "";

        if (iNeedSaveFile == 0) {
            Log.d(TAG, "iNeedSaveFile ==0");
            return "";
        }

        String sLogDir = getSDPath();
        sLogDirend = Util.validFilePath(sLogDir);
        File mLogDirFile = new File(sLogDirend);
        if (!mLogDirFile.exists()) {
            return sb.toString();
        }
        tempath = mLogDirFile + sep + "logs";
        tempathend = Util.validFilePath(tempath);

        File fLogs = new File(tempathend);
        if (!fLogs.exists()) {
            fLogs.mkdir();
        }

        sb.append(mLogDirFile).append(sep).append("logs").append(sep);

        long timestamp = System.currentTimeMillis();
        SimpleDateFormat mDataFormat = new SimpleDateFormat("yyyyMMddHHmmss",
                Locale.CHINA);
        sCurrentTime = mDataFormat.format(new Date(timestamp));

        int iData = mRandom.nextInt();
        sRandomData = Integer.toString(iData);

        String sFileName = sb.append(LogFilePrefix).append(sCurrentTime)
                .append("_").append(sRandomData).append(LogExtension)
                .toString();
        sFileNameEnd = Util.validFilePath(sFileName);

        BufferedWriter writer = null;
        // try {
        File logFile = new File(sFileNameEnd);
        if (!logFile.exists()) {
            if (logFile.createNewFile()) {
                Log.i(TAG, "create log file [" + sFileNameEnd + "] success");
            } else {
                Log.i(TAG, "fail to create log file ");
            }
        }
        Set<Map.Entry<String, NumAndResult>> set = mSyetemResultMap.entrySet();
        Iterator<Map.Entry<String, NumAndResult>> iterator = set.iterator();
        int mIndex;
        boolean bResult;
        StringBuilder contentBuilder = new StringBuilder();
        StringBuilder tabBuilder = new StringBuilder();
        tabBuilder.append("       ");
        while (iterator.hasNext()) {
            Map.Entry<String, NumAndResult> mapentry = (Map.Entry<String, NumAndResult>) iterator
                    .next();
            String sName = mapentry.getKey();
            NumAndResult mTempResult = mapentry.getValue();
            mIndex = mTempResult.mNum;
            bResult = (mTempResult.mResult == ResultDataSave.ITEM_TEST_SUCCES) ? true
                    : false;
            contentBuilder.append(Integer.toString(mIndex)).append(tabBuilder)
                    .append(sName).append(tabBuilder)
                    .append(bResult ? "Pass" : "Fail");
            contentBuilder.append("\n");
        }

        try                 
        {
            writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(new File(sFileNameEnd), true)));
            writer.write(contentBuilder.toString());
            writer.flush();
        } catch (Exception e) 
        {  
            e.printStackTrace();      
        }finally{
            if (writer!=null) {
                Util.safeBwClose(writer);
            }
        }

        iNeedSaveFile = 0;

        return sFileNameEnd;
    }
    
    //add for produce save result in binary
    protected String SaveResultToBinary(int mTestType) throws IOException {
        StringBuilder sb = new StringBuilder("");
        String sCurrentTime = "";
        String sRandomData = "";
        Random mRandom = new Random();
        String tempath = "";
        String tempathend = "";
        String sFileNameEnd = "";
        String sLogDirend = "";

        if (iNeedSaveFile == 0) {
            Log.d(TAG, "iNeedSaveFile ==0");
            return "";
        }

        String sLogDir = getSDPath();
        sLogDirend = Util.validFilePath(sLogDir);
        File mLogDirFile = new File(sLogDirend);
        if (!mLogDirFile.exists()) {
            return sb.toString();
        }
        tempath = mLogDirFile + sep + "logs";
        tempathend = Util.validFilePath(tempath);
        File fLogs = new File(tempathend);
        if (!fLogs.exists()) {
            fLogs.mkdir();
        }

        sb.append(sLogDir).append(sep).append("logs").append(sep);

        String sFileName = sb.append("cittestlog").append(LogTxtExtension).toString();
        sFileNameEnd = Util.validFilePath(sFileName);

        BufferedWriter writer = null;
        // try {
        File logFile = new File(sFileNameEnd);
        if (!logFile.exists()) {
            if (logFile.createNewFile()) {
                Log.i(TAG, "create log file [" + sFileNameEnd + "] success");
            } else {
                Log.i(TAG, "fail to create log file ");
            }
        }
        Set<Map.Entry<String, NumAndResult>> set = mSyetemResultMap.entrySet();
        Iterator<Map.Entry<String, NumAndResult>> iterator = set.iterator();
        int mIndex;
        boolean bResult;
        StringBuilder contentBuilder = new StringBuilder();
        StringBuilder tabBuilder = new StringBuilder();
        tabBuilder.append("       ");
        while (iterator.hasNext()) {
            Map.Entry<String, NumAndResult> mapentry = (Map.Entry<String, NumAndResult>) iterator
                    .next();
            String sName = mapentry.getKey();
            NumAndResult mTempResult = mapentry.getValue();
            mIndex = mTempResult.mNum;
            bResult = (mTempResult.mResult == ResultDataSave.ITEM_TEST_SUCCES) ? true
                    : false;
            contentBuilder.append(bResult ? "1" : "0");
        }

        try                 
        {
            writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(new File(sFileNameEnd), false)));
            writer.write(contentBuilder.toString());
            writer.flush();
        } catch (Exception e) 
        {  
            e.printStackTrace();      
        }finally{
            if (writer!=null) {
                Util.safeBwClose(writer);
            }
        }

        iNeedSaveFile = 0;

        return sFileNameEnd;
    }
    //add end

    public String getSDPath() {
        String externalPath = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            externalPath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath();// 获取跟目录
        }

        Log.i(TAG, "externalPath:" + externalPath);
        return externalPath;

    }
//add by wangsm
    public static void initFactoryResultFile(String value){

        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        Log.d(TAG, "  initFactoryResultFile the path is " + dir.toString());

        if(!dir.exists()){
            dir.mkdirs();
        }

        File resultFile = new File(dir,"factory_result.txt");
        Log.d(TAG, " initFactoryResultFile- >the resultFile path " + resultFile.getPath());
        if(!resultFile.exists()){
            try {
                resultFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.d(TAG, " the resultFile create file " + resultFile.getPath());
            }
        }

        try {
            FileOutputStream fos = new FileOutputStream(resultFile);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));


            try {

                Log.d(TAG, " wangsm ,the init value is " + value);
                writer.write(value);
                writer.flush();
/*                fos.write(value);
                fos.flush();*/
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                if(fos!=null){
                    try {
                        fos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public static String readResultFile(){
        BufferedReader br = null;
        String result = null;
        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File resultFile = new File(dir,"factory_result.txt");
        if(!resultFile.exists()){
            return null;
        }
        try{
            InputStreamReader isr = new InputStreamReader(new FileInputStream(resultFile));
            br = new BufferedReader(isr);
            result = br.readLine();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if (br!=null) {
                Util.safeBrClose(br);
            }
        }

        return result;
    }

    public static void resultSaveToFile(int index,char testResult){

        String value = null;
        String result = readResultFile();
        Log.d(TAG, " wangsm ,the read result is: " + result);
        if(result != null){
            char[] data = result.toCharArray();
            if(index < data.length){
                data[index] = testResult;
                value = String.valueOf(data);
            }else{
                value = result + testResult;
            }

        }


        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

        Log.d(TAG, " the path is path " + dir.toString());

        if(!dir.exists()){
            dir.mkdirs();
        }
/*
        Log.d(TAG, " the filePath is path " + filePath);*/
        File resultFile = new File(dir,"factory_result.txt");
        Log.d(TAG, " the resultFile path " + resultFile.getPath());
        if(!resultFile.exists()){
            try {
                resultFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.d(TAG, " the resultFile create file " + resultFile.getPath());
            }
        }

        try {
            FileOutputStream fos = new FileOutputStream(resultFile);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));


            try {
                if(value == null){
                    value = String.valueOf(testResult);
                }
                Log.d(TAG, " wangsm ,the write value is " + value);
                writer.write(value);
                writer.flush();
/*                fos.write(value);
                fos.flush();*/
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                if(fos!=null){
                    try {
                        fos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static boolean deleteReportFile() {

        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        if(!dir.exists()){
            dir.mkdirs();
        }

        File reportFile = new File(dir, "all_pass_report.txt");
        if(reportFile.isFile() && reportFile.exists()){
            return reportFile.delete();
        }
        return false;
    }
    
    public static void generateReportFile() {

        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

        Log.d(TAG, " the path is path " + dir.toString());

        if(!dir.exists()){
            dir.mkdirs();
        }

        File reportFile = new File(dir, "all_pass_report.txt");
        Log.d(TAG, " the reportFile path " + reportFile.getPath());
        if(!reportFile.exists()){
            try {
                reportFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.d(TAG, " the reportFile create file " + reportFile.getPath());
            }
        }

        try {
            FileOutputStream fos = new FileOutputStream(reportFile);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));

            String value = "all pass";
            try {
                Log.d(TAG, "the write value is " + value);
                writer.write(value);
                writer.flush();
/*                fos.write(value);
                fos.flush();*/
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                if(fos!=null){
                    try {
                        fos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
